import React, { useEffect } from 'react';
import { Button, DatePicker, Space } from 'antd';
import _ from 'lodash';
import moment from 'moment';

import { TjSelect, TjStation, useTRState } from '@/pages/ETrade/components';

const getDateRange = () => {
  return [moment().add(-1, 'months'), moment()];
};

export default ({ power, onChange = () => {} }) => {
  const [state, setState] = useTRState({
    // 表单
    regionItem: null,
    stationIdList: [],
    dates: getDateRange(),
  });

  useEffect(() => {
    power?.[0] && onChangeRegion(power[0], 'search');
  }, [power]);

  /** methods */
  const onChangeRegion = (regionItem, t) => {
    // 切换省份,全选交易单元
    const list = regionItem?.children || [];
    const stations = _.flatten(list.map(({ children }) => children));
    const stationIdList = stations.map((x) => x.value);
    state.regionItem = regionItem;
    state.stationIdList = [...stationIdList];
    setState({
      regionItem,
      stationIdList,
    });
    t === 'search' && _onFinish();
  };

  const _onFinish = async () => {
    // 查询
    const params = {
      provinceId: state.regionItem.provinceId,
      stationIdList: state.stationIdList,
      startDate: state.dates[0].format('YYYY-MM'),
      endDate: state.dates[1].format('YYYY-MM'),
    };
    onChange?.(params);
  };

  const _onReset = () => {
    // 重置&查询
    const dates = getDateRange();
    state.dates = dates;
    setState({
      dates,
    });
    onChangeRegion(power[0], 'search');
  };

  return (
    <Space size={16} wrap>
      <TjSelect
        style={{ width: 160 }}
        value={state.regionItem?.value}
        options={power}
        showSearch
        onChange={(v, opt) => onChangeRegion(opt)}
      />
      <TjStation
        value={state.stationIdList}
        options={state.regionItem?.children || []}
        onChange={(stationIdList) => setState({ stationIdList })}
      />
      <DatePicker.RangePicker
        style={{ width: 256 }}
        value={state.dates}
        picker="month"
        separator="-"
        format={'YYYYMM'}
        allowClear={false}
        onChange={(dates) => setState({ dates })}
      />
      <Space size={16}>
        <Button style={{ width: 98, height: 32 }} type="primary" onClick={_onFinish}>
          查询
        </Button>
        <Button style={{ width: 98, height: 32 }} ghost onClick={_onReset}>
          重置
        </Button>
      </Space>
    </Space>
  );
};
